<template>
  <div class="read-article">
    <!-- 左边菜单目录    -->
    <div class="menu-list">
      <a-directory-tree
          :fieldNames="{children:'items', title:'text'}"
          :blockNode="true"
          @select="handleMenuListSelect"
          :tree-data="treeData"
          v-model:selectedKeys="menuSelected"
      ></a-directory-tree>
    </div>
    <div class="content">
      <!--        <v-md-editor v-model="originText" height="400px"></v-md-editor>-->
      <!--            <v-md-preview height="400px" :text="originText"></v-md-preview>-->
      <div class="markdown-body" v-html="htmlText"></div>
    </div>
    <!-- 小菜单    -->
    <div class="menu-list-small">
      <template v-if="headers.length > 0">
        <a-tree
            class="draggable-tree"
            :tree-data="headers"
            @select="scrollToSection"
            :autoExpandParent="true"
            :blockNode="true"
            :fieldNames="{
            children:'children', title:'content', key:'id'}"
            v-model:selectedKeys="titleOutlineSelected"
        />
      </template>
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref} from 'vue';

import MarkdownIt from 'markdown-it'
import MarkdownItAbbr from 'markdown-it-abbr'
import MarkdownItAnchor from 'markdown-it-anchor'
import MarkdownItFootnote from 'markdown-it-footnote'
import MarkdownItHighlightjs from 'markdown-it-highlightjs'
import MarkdownItSub from 'markdown-it-sub'
import MarkdownItSup from 'markdown-it-sup'
import MarkdownItTasklists from 'markdown-it-task-lists'
import MarkdownItTOC from 'markdown-it-toc-done-right'
import 'highlight.js/styles/default.css'
import 'github-markdown-css';
import imagePlugin from "@/utils/markdown-it/markdown-image-plugin.ts";
import autoLineBreakPlugin from "@/utils/markdown-it/autoLineBreakPlugin.ts";
import extractHeadersPlugin from "@/utils/markdown-it/extractHeadersPlugin.ts";

import {getSidebar} from "@/utils/blogs/sidebarConfig.ts";
// @ts-ignore
import markdownMap from '@markdown-map'


const markdown = new MarkdownIt({
  html: true,
  linkify: true,
  typographer: true
}).use(imagePlugin)
    .use(extractHeadersPlugin)
    // .use(autoLineBreakPlugin)
    .use(MarkdownItAbbr)
    .use(MarkdownItAnchor)
    .use(MarkdownItFootnote)
    .use(MarkdownItHighlightjs)
    .use(MarkdownItSub)
    .use(MarkdownItSup)
    .use(MarkdownItTasklists)
    .use(MarkdownItTOC)

const props = defineProps({
  path: {
    type: String,
    required: true,
  }
});

const treeData = ref([])
const menuSelected = ref([])
// 文章大纲
const headers = ref([]);
const titleOutlineSelected = ref([])


const htmlText = ref('');
const docPath = ref('/archives/01. react 的初步学习.md')
onMounted(async () => {
  treeData.value = getSidebarMenu(props.path)
  for (const key in markdownMap) {
    // 获取当前 key 对应的值
    const value = markdownMap[key];
    htmlText.value = value.htmlContent
    console.log(value.headings)
    let seId = value.headings[0]?.id || ""
    console.log("se id", value.headings[0]?.id)
    titleOutlineSelected.value = [value.headings[0]?.id]
    console.log("titleOutlineSelected", titleOutlineSelected.value)
    headers.value = buildTree(value.headings)
  }

  // comp.value = getMd(props.path).then(res => {
  //   htmlText.value = res.default;
  //   console.log(res.default)
  //   let tocHtml = document.querySelector('.table-of-contents').innerHTML;
  //   console.log(tocHtml)
  // })
  // const env: any = {
  //   docPath: docPath.value,
  //   headers: {}
  // };
  // htmlText.value = markdown.render(md, env);
  // headers.value = createOutline(env.headers)
  nextTick(() => {
    console.log("document.querySelectorAll('img[data-fancybox]')", document.querySelectorAll('img[data-fancybox]'))
    // 获取所有图片元素，并为它们添加点击事件监听器
    document.querySelectorAll('img[data-fancybox]').forEach(img => {
      img.addEventListener('click', event => {
        console.log("addEventListener", event)
        event.preventDefault();

        // 获取图片源 URL
        const src = img.getAttribute('src');

        // 创建并显示弹出层
        const overlay = document.createElement('div');
        overlay.classList.add('image-popup-overlay');

        // 创建并插入大图
        const previewImg = document.createElement('img');
        previewImg.src = src;

        overlay.appendChild(previewImg);

        // 点击关闭弹出层
        overlay.addEventListener('click', () => {
          document.body.removeChild(overlay);
          overlay.style.display = 'none';
        });

        document.body.appendChild(overlay);

        setTimeout(() => {
          overlay.style.display = 'flex';
        }, 10); // 确保过渡动画生效

      });
    });
  })
})

function buildTree(headings) {
  const root = [];
  const stack = [];

  headings.forEach(heading => {
    const node = {
      ...heading,
      children: []
    };

    if (stack.length === 0) {
      root.push(node);
      stack.push(node);
    } else {
      while (stack.length > 0 && stack[stack.length - 1].level >= heading.level) {
        stack.pop();
      }

      if (stack.length === 0) {
        root.push(node);
        stack.push(node);
      } else {
        const parent = stack[stack.length - 1];
        parent.children.push(node);
        stack.push(node);
      }
    }
  });

  return root;
}

const getSidebarMenu = (path) => {
  // 获取 props.path 目录下 sidebar 数据
  return getSidebar(path)
}
/**
 * 点击切换不同的 md 文件
 */
const handleMenuListSelect = async (selectedKeys, e: { selected: boolean, selectedNodes, node, event }) => {
  console.log("handleMenuListChange", selectedKeys)
  console.log("handleMenuListChange", e)
  const {link} = e.node
  // 获取文章地址
  console.log(e.node.link)
  console.log(markdownMap)
  docPath.value = link
  const key = 'src/blogs' + link
  // 将 key 中的 / 换成 \\
  const key2 = key.replace(/\//g, '\\');
  const md = markdownMap[key2]
  htmlText.value = md.htmlContent
  headers.value = buildTree(md.headings)
}

function scrollToSection(selectedKeys, e: { selected: boolean, selectedNodes, node, event }) {
  console.log("handleMenuListChange", selectedKeys[0])
  console.log("handleMenuListChange", e)
  let id = e.node.id;
  const element = document.getElementById(id);
  console.log("element", element)
  if (element) {
    element.scrollIntoView({behavior: 'smooth'});
  }
}

</script>

<style scoped lang="scss">
.read-article {
  display: flex;
  width: 100%;
  height: calc(100vh - $blog-nav-height);

  .menu-list {
    min-width: 300px;
    height: 100%;
    /*右边框宽度为 2px 的灰色实线*/
    border-right: 5px solid #ccc;

    //box-shadow: 1px 0 6px rgba(0, 0, 0, .12);

    padding: 6px;
    /*溢出展示 y 轴 滚动*/
    overflow-y: scroll;

    li {
      background-color: #00c0fa;

      a {
        display: block;
        padding: 10px;
        border-radius: 4px;
        background-color: #fafafa;
        color: #333;

        &:hover {
          background-color: #e6e6e6;
        }
      }
    }
  }

  .content {
    width: calc(100vw - $blog-archives-width);
    height: 100%;
    padding: 0 20px;
    overflow-y: scroll;

    .markdown-body {
      box-sizing: border-box;
      min-width: 200px;
      max-width: 100%;
      margin: 0 auto;
      padding: 45px;
    }
  }
}

.menu-list-small {
  padding: 20px 0;
  width: 420px;
  height: 100%;
  /*左边边框阴影*/
  box-shadow: -1px 0 6px rgba(0, 0, 0, .12);
}

.table-of-contents {
  display: none; /* 隐藏原始位置的大纲 */
}


</style>
